package com.igeek.boot.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @Author fengqq
 * @Description TODO
 * @Date 2024/9/4  15:42
 */
@Configuration
public class RedisConfig {

    //注意：一定要替换底层组件 RedisTemplate<String, Object>
    //默认的底层组件RedisTemplate<Object, Object>  它的序列化的格式是 \xac\xed\x00\x05t\x00\boid::203 不方便来查看keyvalue

    //替换底层组件RedisTemplate<Object, Object> 生效的是RedisTemplate<String, Object>
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        //创建序列化对象
        //value 序列化的规则 Object对象转换为json格式
        GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer =
                new GenericJackson2JsonRedisSerializer();
        //key 序列化的规则 key存储的是string字符串
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

        //设置key  序列化
        template.setKeySerializer(stringRedisSerializer);
        template.setHashKeySerializer(stringRedisSerializer);
        //设置value  序列化
        template.setValueSerializer(genericJackson2JsonRedisSerializer);
        template.setHashValueSerializer(genericJackson2JsonRedisSerializer);

        //设置连接工厂
        template.setConnectionFactory(redisConnectionFactory);
        //执行bean实例的初始化
        template.afterPropertiesSet();
        return template;
    }
}
